<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="UTF-8">
        <title>baidu</title>
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
    <div id="app">
       <switchbtn :result="result" @on-result-change="onResultChange"></switchbtn>
       <input type="button" value="change" @click="change">
    </div>
</body>
<script type="text/javascript">
        Vue.component("switchbtn", {
        template: "<div @click='change'>{{myResult?'开':'关'}}</div>",
        props: ["result"],
        data: function () {
            return {
                myResult: this.result//①创建props属性result的副本--myResult
            }
        },
        watch: {
            /* 此处是重点 */
            result(val) {
                this.myResult = val;//②监听外部对props属性result的变更，并同步到组件内的data属性myResult中
            },
            myResult(val){
                this.$emit("on-result-change",val);//③组件内对myResult变更后向外部发送事件通知
            }
        },
        methods: {
            change() {
                this.myResult = !this.myResult;
            }
        }
    });
 
    new Vue({
        el: "#app",
        data: {
            result: true
        },
        methods: {
            // 外部触发方法
            change() {
                this.result = !this.result;
            },
            // 接收
            onResultChange(val){
                this.result=val;//④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
            }
        }
    });
</script>
</html>